var http = require('http');
var fs = require('fs');
var url = require('url');
var MongoClient = require('mongodb').MongoClient;
var mongoUrl = "mongodb://lional:zhou123456@localhost:27017//?authSource=admin";

// 创建服务器
http.createServer(function (request, response) {
  // 解析请求，包括文件名
  let theUrl = url.parse(request.url, true) //true在解析query时会转换为对象，false为字符串
  let id = theUrl.query.id
  let pathname = theUrl.pathname

  //从数据库查找
  function searchById(collection, id) {
    let promise = new Promise((resolve, rejected) => {
      MongoClient.connect(mongoUrl, {
        useNewUrlParser: true
      }, function (err, db) {
        if (err) throw err
        console.log("数据库连接成功！")
        collection = collection.slice(1, collection.length - 1)
        console.log("需要查找的" + collection + "Id: " + id)
        let blog = db.db("blog")
        blog.collection(collection).find({
          "id": Number(id)
        }).toArray(function (err, res) {
          if (err) throw err
          console.log(res)
          if (collection === "pages") {
            //如果是查询pages，直接返回查询结果
            resolve(res)
          } else if (collection === "tags") {
            //如果查询tags，则需要返回tags中所包含的pages具体内容
            let pages = []
            console.log("res.pages:" + res[0].pages)
            res[0].pages.forEach(element => {
              pages.push({"id": element})
            })
            console.log("need to search:" + pages)
            blog.collection("pages").find({
              $or: pages
            }).toArray(function (err, res) {
              if (err) throw err
              console.log("search result:" + res)
              resolve(res)
            })
          }
          db.close()
        })
      })
    }).then(
      data => {
        response.writeHead(200, {
          'Content-Type': "application/json",
        })
        response.write(JSON.stringify(data))
        response.end()
      },
      reason => {
        console.log(reason)
      }
    )
  }

  // 输出请求的地址
  console.log("Request for " + theUrl.path + " received.");
  searchById(pathname, id)
  
}).listen(4000);

// 控制台会输出以下信息
console.log('Server running at http://127.0.0.1:4000/');